package com.jyniubi.core.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Base64;

@Configuration
@Slf4j
public class RabbitmqConfig {
    @Resource
    RabbitTemplate rabbitTemplate;
    //需要依赖注入完成后立即执行的初始化逻辑，只执行一次，无参数，必须返回void，非阻塞，自动调用
    @PostConstruct
    public void init(){
        //消息未到达队列的回调
        rabbitTemplate.setReturnCallback((Message message, int replyCode, String replyText, String exchange, String routingKey)->{
            log.error("消息未到达队列：replyCode->{} , replyText->{} , exchange->{},routingKey->{} , message->{}",
                    replyCode,replyText,exchange,routingKey, Base64.getEncoder().encode(message.getBody()));
        });
        //消息未到达交换机的回调
        rabbitTemplate.setConfirmCallback(( CorrelationData correlationData, boolean ack, String cause)->{
            if(!ack){//消息未到达交换机
                log.error("消息未到达队列：cause->{}",cause);
            }
        });
    }
}
